昨天提到設置完CollectionViewLayout,今天來講客製化Cell以及委派。
如果仔細看到昨天的代碼,其實我已經把委派寫好了,只是留著今天才講,就是下面這兩行:
     self.firstCollectionView.dataSource = self
     self.firstCollectionView.delegate = self
另外需要ViewController遵從(comfirm)UICollectionViewDataSource, UICollectionViewDelegate,我另外寫在extension內,比較好辨別:
    extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate
    {
    這邊內容是遵從協議需要實作的方法...
    可以等一下子讓錯誤跳出來,點選fix,就會自動補全這些方法
    }
補全錯誤之後,現在你的extension內應該長得像這樣子:
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate
{
以下這兩個方法都是遵從UICollectionViewDataSource需要實作的方法,至於UICollectionViewDelegate在目前的功能內其實沒有用到,不過我先寫上去,之後可能需要一些點擊事件的時候會用到。
//定義section內有多少列
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}
    
//定義每列的內容長啥樣子
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}
    
}
是時候開始實作這兩個方法了,首先要決定顯示多少Cell,取決於你的資料數量,我們來做一筆資料讓firstCollectionView可以顯示,在ViewController一開始處宣告以下代碼。
var dataNumber: [Int] =
    {
        var array = [Int]()
        for i in 1...10
        {
            array.append(i)
        }
        return array
    }()
    var dataEnglish: [String] =
    {
        var array = [String]()
        for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        {
            array.append(String(i))
        }
        return array
    }()
如上所示,我做了一個1~10以及A~Z的陣列,我打算讓firstCollectionView使用dataNumber,secondCollectinView使用dataEnglish,不過目前只有firstCollectionView,所以先專注於firstCollectionView的設置就好。
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    {
        return dataNumber.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    {  
        let firstCell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCellIdentifier.firstCell.identifier , for: indexPath) as! CardCell
        firstCell.setupFirst(data: dataNumber, indexPath: indexPath)
        return firstCell
    }
}
你會發現我剛剛沒有提到CardCell這個類別以及這個類別內的方法setupFirst(data:indexPath:),由於我們的Cell是要客製化的,所以我們另外用一個類別來管理它,並且我想要讓controller跟view分離,所以用setupFirst(data:indexPath:)這個方法來管理Cell的顯示。
那為什麼UICollectionView就沒有跟控制器分離呢? 因為比較複雜,並且這次是專注在實作CollectionView,所以我就沒有在這部分多做。
明天繼續來講另外用單獨的類別管理Cell,以及這個類別要如何取得到ViewController的資料。